import {
	tips
} from "./tips";
import {
	getToken,
	getConn,
} from "@/store/user.js";

const silentUrl = ['/basic/captchaImage'];

const errHandler = (err) => {
	if (err?.data?.msg) tips("错误", err?.data?.msg);
	else tips("错误", "操作失败");
	return Promise.reject(err);
};

export const fetch = (method, url, params = {}, data = {}, errMsg, hasToken = true, showTitle) =>
	new Promise(async (resolve, reject) => {
		const that = this;
		const token = getToken();
		let header = {
			Accept: "application/json, text/plain, */*",
			"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
			"content-type": "application/json",
		};
		if (hasToken) {
			header['Token'] = token;
		}
		let arr = [];
		for (const key in params) {
			if (Object.hasOwnProperty.call(params, key)) {
				const element = params[key];
				if (element) arr.push(`${key}=${element}`);
			}
		}

		let baseUrl = '';
		// #ifdef H5
		// 如需跨域参照以下h5跨域配置
		baseUrl = "/api"
		// baseUrl = getConn().mes;
		// #endif

		// #ifdef APP-PLUS
		baseUrl = getConn().mes;
		// #endif
		console.log('fetch url =>', `${baseUrl}${url}${arr.length > 0 ? "?" + arr.join("&") : ""}`);
		uni.request({
			method,
			url: `${baseUrl}${url}${arr.length > 0 ? "?" + arr.join("&") : ""}`,
			header,
			data,
			success(res) {
				if (res.data.code == "200") {
					return resolve(res.data.data);
				} else if (res.data.code == "1" && res.data.msg) {
					if (showTitle) {
						// 特殊请求 code==1 需要交互操作
						return resolve(res.data);
					} else {
						uni.showModal({
							title: '提示',
							content: res.data.msg,
							showCancel: false,
							success: function(res) {}
						});
					}
				} else {
					return reject(res.data);
				}
			},
			fail(err) {
				return reject(err);
			},
			complete(res) {
				// console.log('url', url);
				// console.log('data', data);
				// console.log('res', res);
				if (res.data.code == 401) {
					uni.redirectTo({
						url: '/pages/login/index'
					});
				}
			},
		});
	}).catch((res) => {
		// 静默URL 不提示错误信息
		if (silentUrl.indexOf(url) === -1) {
			tips("错误", errMsg ? errMsg : res.msg ? res.msg : "网络异常...");
		}
		return Promise.reject({});
	});
export default fetch;